package com.huanqiu.mylib.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.huanqiu.mylib.R;

/**
 * 通用 Fragment 容器 Activity
 */
public class FragmentContainerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_container);

        Intent intent = getIntent();
        String fragmentName = intent.getStringExtra("fragmentName");
        Bundle param = intent.getBundleExtra("param");

        Class<Fragment> fragmentClass = null;
        try {
            fragmentClass = (Class<Fragment>) Class.forName(fragmentName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (fragmentClass != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .add(R.id.fragment_container, fragmentClass, param)
                    .commit();
        }
    }

    // 加载某个 Fragment
    public static void open(@NonNull Context context,
                            @NonNull Class<? extends Fragment> fragmentClass,
                            @Nullable Bundle args) {
        Intent intent = new Intent(context, FragmentContainerActivity.class);
        intent.putExtra("fragmentName", fragmentClass.getName());
        intent.putExtra("param", args);
        context.startActivity(intent);
    }

}
